<!DOCTYPE html>
<html lang="en-us">
  <head>

    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    
<meta charset="UTF-8">
<title>Terms Aggregation | Elasticsearch Guide [7.7] | Elastic</title>
<link rel="home" href="index.html" title="Elasticsearch Guide [7.7]">
<link rel="up" href="search-aggregations-bucket.html" title="Bucket Aggregations">
<link rel="prev" href="search-aggregations-bucket-significanttext-aggregation.html" title="Significant Text Aggregation">
<link rel="next" href="search-aggregations-bucket-range-field-note.html" title="Subtleties of bucketing range fields">
<meta name="DC.type" content="Learn/Docs/Elasticsearch/Reference/7.7">
<meta name="DC.subject" content="Elasticsearch">
<meta name="DC.identifier" content="7.7">
<meta name="robots" content="noindex,nofollow">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdn.optimizely.com/js/18132920325.js"></script>
    <link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png">
    <link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32">
    <link rel="icon" type="image/png" href="/android-chrome-192x192.png" sizes="192x192">
    <link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96">
    <link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16">
    <link rel="manifest" href="/manifest.json">
    <meta name="apple-mobile-web-app-title" content="Elastic">
    <meta name="application-name" content="Elastic">
    <meta name="msapplication-TileColor" content="#ffffff">
    <meta name="msapplication-TileImage" content="/mstile-144x144.png">
    <meta name="theme-color" content="#ffffff">
    <meta name="naver-site-verification" content="936882c1853b701b3cef3721758d80535413dbfd">
    <meta name="yandex-verification" content="d8a47e95d0972434">
    <meta name="localized" content="true">
    <meta name="st:robots" content="follow,index">
    <meta property="og:image" content="https://www.elastic.co/static/images/elastic-logo-200.png">
    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
    <link rel="icon" href="/favicon.ico" type="image/x-icon">
    <link rel="apple-touch-icon-precomposed" sizes="64x64" href="/favicon_64x64_16bit.png">
    <link rel="apple-touch-icon-precomposed" sizes="32x32" href="/favicon_32x32.png">
    <link rel="apple-touch-icon-precomposed" sizes="16x16" href="/favicon_16x16.png">
    <!-- Give IE8 a fighting chance -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <link rel="stylesheet" type="text/css" href="/guide/static/styles.css">
  </head>

  <!--© 2015-2021 Elasticsearch B.V. Copying, publishing and/or distributing without written permission is strictly prohibited.-->

  <body>
    <!-- Google Tag Manager -->
    <script>dataLayer = [];</script><noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-58RLH5" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
    <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= '//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-58RLH5');</script>
    <!-- End Google Tag Manager -->

    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-12395217-16"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
      gtag('config', 'UA-12395217-16');
    </script>

    <!--BEGIN QUALTRICS WEBSITE FEEDBACK SNIPPET-->
    <script type="text/javascript">
      (function(){var g=function(e,h,f,g){
      this.get=function(a){for(var a=a+"=",c=document.cookie.split(";"),b=0,e=c.length;b<e;b++){for(var d=c[b];" "==d.charAt(0);)d=d.substring(1,d.length);if(0==d.indexOf(a))return d.substring(a.length,d.length)}return null};
      this.set=function(a,c){var b="",b=new Date;b.setTime(b.getTime()+6048E5);b="; expires="+b.toGMTString();document.cookie=a+"="+c+b+"; path=/; "};
      this.check=function(){var a=this.get(f);if(a)a=a.split(":");else if(100!=e)"v"==h&&(e=Math.random()>=e/100?0:100),a=[h,e,0],this.set(f,a.join(":"));else return!0;var c=a[1];if(100==c)return!0;switch(a[0]){case "v":return!1;case "r":return c=a[2]%Math.floor(100/c),a[2]++,this.set(f,a.join(":")),!c}return!0};
      this.go=function(){if(this.check()){var a=document.createElement("script");a.type="text/javascript";a.src=g;document.body&&document.body.appendChild(a)}};
      this.start=function(){var a=this;window.addEventListener?window.addEventListener("load",function(){a.go()},!1):window.attachEvent&&window.attachEvent("onload",function(){a.go()})}};
      try{(new g(100,"r","QSI_S_ZN_emkP0oSe9Qrn7kF","https://znemkp0ose9qrn7kf-elastic.siteintercept.qualtrics.com/WRSiteInterceptEngine/?Q_ZID=ZN_emkP0oSe9Qrn7kF")).start()}catch(i){}})();
    </script><div id="ZN_emkP0oSe9Qrn7kF"><!--DO NOT REMOVE-CONTENTS PLACED HERE--></div>
    <!--END WEBSITE FEEDBACK SNIPPET-->

    <div id="elastic-nav" style="display:none;"></div>
    <script src="https://www.elastic.co/elastic-nav.js"></script>

    <!-- Subnav -->
    <div>
      <div>
        <div class="tertiary-nav d-none d-md-block">
          <div class="container">
            <div class="p-t-b-15 d-flex justify-content-between nav-container">
              <div class="breadcrum-wrapper"><span><a href="/guide/" style="font-size: 14px; font-weight: 600; color: #000;">Docs</a></span></div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="main-container">
      <section id="content">
        <div class="content-wrapper">

          <section id="guide" lang="en">
            <div class="container">
              <div class="row">
                <div class="col-xs-12 col-sm-8 col-md-8 guide-section">
                  <!-- start body -->
                  <div class="page_header">
<strong>IMPORTANT</strong>: No additional bug fixes or documentation updates
will be released for this version. For the latest information, see the
<a href="../current/index.html">current release documentation</a>.
</div>
<div id="content">
<div class="breadcrumbs">
<span class="breadcrumb-link"><a href="index.html">Elasticsearch Guide [7.7]</a></span>
»
<span class="breadcrumb-link"><a href="search-aggregations.html">Aggregations</a></span>
»
<span class="breadcrumb-link"><a href="search-aggregations-bucket.html">Bucket Aggregations</a></span>
»
<span class="breadcrumb-node">Terms Aggregation</span>
</div>
<div class="navheader">
<span class="prev">
<a href="search-aggregations-bucket-significanttext-aggregation.html">« Significant Text Aggregation</a>
</span>
<span class="next">
<a href="search-aggregations-bucket-range-field-note.html">Subtleties of bucketing range fields »</a>
</span>
</div>
<div class="section">
<div class="titlepage"><div><div>
<h2 class="title">
<a id="search-aggregations-bucket-terms-aggregation"></a>Terms Aggregation<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/terms-aggregation.asciidoc">edit</a>
</h2>
</div></div></div>
<p>A multi-bucket value source based aggregation where buckets are dynamically built - one per unique value.</p>
<p>Example:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET /_search
{
    "aggs" : {
        "genres" : {
            "terms" : { "field" : "genre" } <a id="CO242-1"></a><i class="conum" data-value="1"></i>
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/522.console"></div>
<div class="calloutlist">
<table border="0" summary="Callout list">
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO242-1"><i class="conum" data-value="1"></i></a></p>
</td>
<td align="left" valign="top">
<p><code class="literal">terms</code> aggregation should be a field of type <code class="literal">keyword</code> or any other data type suitable for bucket aggregations. In order to use it with <code class="literal">text</code> you will need to enable
<a class="xref" href="fielddata.html" title="fielddata">fielddata</a>.</p>
</td>
</tr>
</table>
</div>
<p>Response:</p>
<div class="pre_wrapper lang-console-result">
<pre class="programlisting prettyprint lang-console-result">{
    ...
    "aggregations" : {
        "genres" : {
            "doc_count_error_upper_bound": 0, <a id="CO243-1"></a><i class="conum" data-value="1"></i>
            "sum_other_doc_count": 0, <a id="CO243-2"></a><i class="conum" data-value="2"></i>
            "buckets" : [ <a id="CO243-3"></a><i class="conum" data-value="3"></i>
                {
                    "key" : "electronic",
                    "doc_count" : 6
                },
                {
                    "key" : "rock",
                    "doc_count" : 3
                },
                {
                    "key" : "jazz",
                    "doc_count" : 2
                }
            ]
        }
    }
}</pre>
</div>
<div class="calloutlist">
<table border="0" summary="Callout list">
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO243-1"><i class="conum" data-value="1"></i></a></p>
</td>
<td align="left" valign="top">
<p>an upper bound of the error on the document counts for each term, see <a class="xref" href="search-aggregations-bucket-terms-aggregation.html#search-aggregations-bucket-terms-aggregation-approximate-counts" title="Document counts are approximate">below</a></p>
</td>
</tr>
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO243-2"><i class="conum" data-value="2"></i></a></p>
</td>
<td align="left" valign="top">
<p>when there are lots of unique terms, Elasticsearch only returns the top terms; this number is the sum of the document counts for all buckets that are not part of the response</p>
</td>
</tr>
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO243-3"><i class="conum" data-value="3"></i></a></p>
</td>
<td align="left" valign="top">
<p>the list of the top buckets, the meaning of <code class="literal">top</code> being defined by the <a class="xref" href="search-aggregations-bucket-terms-aggregation.html#search-aggregations-bucket-terms-aggregation-order" title="Order">order</a></p>
</td>
</tr>
</table>
</div>
<p>By default, the <code class="literal">terms</code> aggregation will return the buckets for the top ten terms ordered by the <code class="literal">doc_count</code>. One can
change this default behaviour by setting the <code class="literal">size</code> parameter.</p>
<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="search-aggregations-bucket-terms-aggregation-size"></a>Size<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/terms-aggregation.asciidoc">edit</a>
</h3>
</div></div></div>
<p>The <code class="literal">size</code> parameter can be set to define how many term buckets should be returned out of the overall terms list. By
default, the node coordinating the search process will request each shard to provide its own top <code class="literal">size</code> term buckets
and once all shards respond, it will reduce the results to the final list that will then be returned to the client.
This means that if the number of unique terms is greater than <code class="literal">size</code>, the returned list is slightly off and not accurate
(it could be that the term counts are slightly off and it could even be that a term that should have been in the top
size buckets was not returned).</p>
<div class="note admon">
<div class="icon"></div>
<div class="admon_content">
<p>If you want to retrieve <span class="strong strong"><strong>all</strong></span> terms or all combinations of terms in a nested <code class="literal">terms</code> aggregation
      you should use the <a class="xref" href="search-aggregations-bucket-composite-aggregation.html" title="Composite aggregation">Composite</a> aggregation which
      allows to paginate over all possible terms rather than setting a size greater than the cardinality of the field in the
      <code class="literal">terms</code> aggregation. The <code class="literal">terms</code> aggregation is meant to return the <code class="literal">top</code> terms and does not allow pagination.</p>
</div>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="search-aggregations-bucket-terms-aggregation-approximate-counts"></a>Document counts are approximate<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/terms-aggregation.asciidoc">edit</a>
</h3>
</div></div></div>
<p>Document counts (and the results of any sub aggregations) in the terms
aggregation are not always accurate. Each shard provides its own view of what
the ordered list of terms should be. These views are combined to give a final
view.</p>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="_shard_size_3"></a>Shard Size<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/terms-aggregation.asciidoc">edit</a>
</h3>
</div></div></div>
<p>The higher the requested <code class="literal">size</code> is, the more accurate the results will be, but also, the more expensive it will be to
compute the final results (both due to bigger priority queues that are managed on a shard level and due to bigger data
transfers between the nodes and the client).</p>
<p>The <code class="literal">shard_size</code> parameter can be  used to minimize the extra work that comes with bigger requested <code class="literal">size</code>. When defined,
it will determine how many terms the coordinating node will request from each shard. Once all the shards responded, the
coordinating node will then reduce them to a final result which will be based on the <code class="literal">size</code> parameter - this way,
one can increase the accuracy of the returned terms and avoid the overhead of streaming a big list of buckets back to
the client.</p>
<div class="note admon">
<div class="icon"></div>
<div class="admon_content">
<p><code class="literal">shard_size</code> cannot be smaller than <code class="literal">size</code> (as it doesn’t make much sense). When it is, Elasticsearch will
        override it and reset it to be equal to <code class="literal">size</code>.</p>
</div>
</div>
<p>The default <code class="literal">shard_size</code> is <code class="literal">(size * 1.5 + 10)</code>.</p>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="_calculating_document_count_error"></a>Calculating Document Count Error<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/terms-aggregation.asciidoc">edit</a>
</h3>
</div></div></div>
<p>There are two error values which can be shown on the terms aggregation. The first gives a value for the aggregation as
a whole which represents the maximum potential document count for a term which did not make it into the final list of
terms. This is calculated as the sum of the document count from the last term returned from each shard.</p>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="_per_bucket_document_count_error"></a>Per bucket document count error<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/terms-aggregation.asciidoc">edit</a>
</h3>
</div></div></div>
<p>The second error value can be enabled by setting the <code class="literal">show_term_doc_count_error</code> parameter to true:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET /_search
{
    "aggs" : {
        "products" : {
            "terms" : {
                "field" : "product",
                "size" : 5,
                "show_term_doc_count_error": true
            }
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/523.console"></div>
<p>This shows an error value for each term returned by the aggregation which represents the <em>worst case</em> error in the document count
and can be useful when deciding on a value for the <code class="literal">shard_size</code> parameter. This is calculated by summing the document counts for
the last term returned by all shards which did not return the term.</p>
<p>These errors can only be calculated in this way when the terms are ordered by descending document count. When the aggregation is
ordered by the terms values themselves (either ascending or descending) there is no error in the document count since if a shard
does not return a particular term which appears in the results from another shard, it must not have that term in its index. When the
aggregation is either sorted by a sub aggregation or in order of ascending document count, the error in the document counts cannot be
determined and is given a value of -1 to indicate this.</p>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="search-aggregations-bucket-terms-aggregation-order"></a>Order<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/terms-aggregation.asciidoc">edit</a>
</h3>
</div></div></div>
<p>The order of the buckets can be customized by setting the <code class="literal">order</code> parameter. By default, the buckets are ordered by
their <code class="literal">doc_count</code> descending.  It is possible to change this behaviour as documented below:</p>
<div class="warning admon">
<div class="icon"></div>
<div class="admon_content">
<p>Sorting by ascending <code class="literal">_count</code> or by sub aggregation is discouraged as it increases the
<a class="xref" href="search-aggregations-bucket-terms-aggregation.html#search-aggregations-bucket-terms-aggregation-approximate-counts" title="Document counts are approximate">error</a> on document counts.
It is fine when a single shard is queried, or when the field that is being aggregated was used
as a routing key at index time: in these cases results will be accurate since shards have disjoint
values. However otherwise, errors are unbounded. One particular case that could still be useful
is sorting by <a class="xref" href="search-aggregations-metrics-min-aggregation.html" title="Min Aggregation"><code class="literal">min</code></a> or
<a class="xref" href="search-aggregations-metrics-max-aggregation.html" title="Max Aggregation"><code class="literal">max</code></a> aggregation: counts will not be accurate
but at least the top buckets will be correctly picked.</p>
</div>
</div>
<p>Ordering the buckets by their doc <code class="literal">_count</code> in an ascending manner:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET /_search
{
    "aggs" : {
        "genres" : {
            "terms" : {
                "field" : "genre",
                "order" : { "_count" : "asc" }
            }
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/524.console"></div>
<p>Ordering the buckets alphabetically by their terms in an ascending manner:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET /_search
{
    "aggs" : {
        "genres" : {
            "terms" : {
                "field" : "genre",
                "order" : { "_key" : "asc" }
            }
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/525.console"></div>
<div class="warning admon">
<div class="icon"></div>
<div class="admon_content">
<h3>Deprecated in 6.0.0.</h3>
<p>Use <code class="literal">_key</code> instead of <code class="literal">_term</code> to order buckets by their term</p>
</div>
</div>
<p>Ordering the buckets by single value metrics sub-aggregation (identified by the aggregation name):</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET /_search
{
    "aggs" : {
        "genres" : {
            "terms" : {
                "field" : "genre",
                "order" : { "max_play_count" : "desc" }
            },
            "aggs" : {
                "max_play_count" : { "max" : { "field" : "play_count" } }
            }
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/526.console"></div>
<p>Ordering the buckets by multi value metrics sub-aggregation (identified by the aggregation name):</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET /_search
{
    "aggs" : {
        "genres" : {
            "terms" : {
                "field" : "genre",
                "order" : { "playback_stats.max" : "desc" }
            },
            "aggs" : {
                "playback_stats" : { "stats" : { "field" : "play_count" } }
            }
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/527.console"></div>
<div class="note admon">
<div class="icon"></div>
<div class="admon_content">
<h3>Pipeline aggs cannot be used for sorting</h3>
<p><a class="xref" href="search-aggregations-pipeline.html" title="Pipeline Aggregations">Pipeline aggregations</a> are run during the
reduce phase after all other aggregations have already completed.  For this
reason, they cannot be used for ordering.</p>
</div>
</div>
<p>It is also possible to order the buckets based on a "deeper" aggregation in the hierarchy. This is supported as long
as the aggregations path are of a single-bucket type, where the last aggregation in the path may either be a single-bucket
one or a metrics one. If it’s a single-bucket type, the order will be defined by the number of docs in the bucket (i.e. <code class="literal">doc_count</code>),
in case it’s a metrics one, the same rules as above apply (where the path must indicate the metric name to sort by in case of
a multi-value metrics aggregation, and in case of a single-value metrics aggregation the sort will be applied on that value).</p>
<p>The path must be defined in the following form:</p>
<div class="pre_wrapper lang-ebnf">
<pre class="programlisting prettyprint lang-ebnf">AGG_SEPARATOR       =  '&gt;' ;
METRIC_SEPARATOR    =  '.' ;
AGG_NAME            =  &lt;the name of the aggregation&gt; ;
METRIC              =  &lt;the name of the metric (in case of multi-value metrics aggregation)&gt; ;
PATH                =  &lt;AGG_NAME&gt; [ &lt;AGG_SEPARATOR&gt;, &lt;AGG_NAME&gt; ]* [ &lt;METRIC_SEPARATOR&gt;, &lt;METRIC&gt; ] ;</pre>
</div>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET /_search
{
    "aggs" : {
        "countries" : {
            "terms" : {
                "field" : "artist.country",
                "order" : { "rock&gt;playback_stats.avg" : "desc" }
            },
            "aggs" : {
                "rock" : {
                    "filter" : { "term" : { "genre" :  "rock" }},
                    "aggs" : {
                        "playback_stats" : { "stats" : { "field" : "play_count" }}
                    }
                }
            }
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/528.console"></div>
<p>The above will sort the artist’s countries buckets based on the average play count among the rock songs.</p>
<p>Multiple criteria can be used to order the buckets by providing an array of order criteria such as the following:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET /_search
{
    "aggs" : {
        "countries" : {
            "terms" : {
                "field" : "artist.country",
                "order" : [ { "rock&gt;playback_stats.avg" : "desc" }, { "_count" : "desc" } ]
            },
            "aggs" : {
                "rock" : {
                    "filter" : { "term" : { "genre" : "rock" }},
                    "aggs" : {
                        "playback_stats" : { "stats" : { "field" : "play_count" }}
                    }
                }
            }
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/529.console"></div>
<p>The above will sort the artist’s countries buckets based on the average play count among the rock songs and then by
their <code class="literal">doc_count</code> in descending order.</p>
<div class="note admon">
<div class="icon"></div>
<div class="admon_content">
<p>In the event that two buckets share the same values for all order criteria the bucket’s term value is used as a
tie-breaker in ascending alphabetical order to prevent non-deterministic ordering of buckets.</p>
</div>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="_minimum_document_count_4"></a>Minimum document count<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/terms-aggregation.asciidoc">edit</a>
</h3>
</div></div></div>
<p>It is possible to only return terms that match more than a configured number of hits using the <code class="literal">min_doc_count</code> option:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET /_search
{
    "aggs" : {
        "tags" : {
            "terms" : {
                "field" : "tags",
                "min_doc_count": 10
            }
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/530.console"></div>
<p>The above aggregation would only return tags which have been found in 10 hits or more. Default value is <code class="literal">1</code>.</p>
<p>Terms are collected and ordered on a shard level and merged with the terms collected from other shards in a second step. However, the shard does not have the information about the global document count available. The decision if a term is added to a candidate list depends only on the order computed on the shard using local shard frequencies. The <code class="literal">min_doc_count</code> criterion is only applied after merging local terms statistics of all shards. In a way the decision to add the term as a candidate is made without being very <em>certain</em> about if the term will actually reach the required <code class="literal">min_doc_count</code>. This might cause many (globally) high frequent terms to be missing in the final result if low frequent terms populated the candidate lists. To avoid this, the <code class="literal">shard_size</code> parameter can be increased to allow more candidate terms on the shards. However, this increases memory consumption and network traffic.</p>
<p><code class="literal">shard_min_doc_count</code> parameter</p>
<p>The parameter <code class="literal">shard_min_doc_count</code> regulates the <em>certainty</em> a shard has if the term should actually be added to the candidate list or not with respect to the <code class="literal">min_doc_count</code>. Terms will only be considered if their local shard frequency within the set is higher than the <code class="literal">shard_min_doc_count</code>. If your dictionary contains many low frequent terms and you are not interested in those (for example misspellings), then you can set the <code class="literal">shard_min_doc_count</code> parameter to filter out candidate terms on a shard level that will with a reasonable certainty not reach the required <code class="literal">min_doc_count</code> even after merging the local counts. <code class="literal">shard_min_doc_count</code> is set to <code class="literal">0</code> per default and has no effect unless you explicitly set it.</p>
<div class="note admon">
<div class="icon"></div>
<div class="admon_content">
<p>Setting <code class="literal">min_doc_count</code>=<code class="literal">0</code> will also return buckets for terms that didn’t match any hit. However, some of
         the returned terms which have a document count of zero might only belong to deleted documents or documents
         from other types, so there is no warranty that a <code class="literal">match_all</code> query would find a positive document count for
         those terms.</p>
</div>
</div>
<div class="warning admon">
<div class="icon"></div>
<div class="admon_content">
<p>When NOT sorting on <code class="literal">doc_count</code> descending, high values of <code class="literal">min_doc_count</code> may return a number of buckets
         which is less than <code class="literal">size</code> because not enough data was gathered from the shards. Missing buckets can be
         back by increasing <code class="literal">shard_size</code>.
         Setting <code class="literal">shard_min_doc_count</code> too high will cause terms to be filtered out on a shard level. This value should be set much lower than <code class="literal">min_doc_count/#shards</code>.</p>
</div>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="search-aggregations-bucket-terms-aggregation-script"></a>Script<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/terms-aggregation.asciidoc">edit</a>
</h3>
</div></div></div>
<p>Generating the terms using a script:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET /_search
{
    "aggs" : {
        "genres" : {
            "terms" : {
                "script" : {
                    "source": "doc['genre'].value",
                    "lang": "painless"
                }
            }
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/531.console"></div>
<p>This will interpret the <code class="literal">script</code> parameter as an <code class="literal">inline</code> script with the default script language and no script parameters. To use a stored script use the following syntax:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET /_search
{
    "aggs" : {
        "genres" : {
            "terms" : {
                "script" : {
                    "id": "my_script",
                    "params": {
                        "field": "genre"
                    }
                }
            }
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/532.console"></div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="_value_script_9"></a>Value Script<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/terms-aggregation.asciidoc">edit</a>
</h3>
</div></div></div>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET /_search
{
    "aggs" : {
        "genres" : {
            "terms" : {
                "field" : "genre",
                "script" : {
                    "source" : "'Genre: ' +_value",
                    "lang" : "painless"
                }
            }
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/533.console"></div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="_filtering_values_4"></a>Filtering Values<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/terms-aggregation.asciidoc">edit</a>
</h3>
</div></div></div>
<p>It is possible to filter the values for which buckets will be created. This can be done using the <code class="literal">include</code> and
<code class="literal">exclude</code> parameters which are based on regular expression strings or arrays of exact values. Additionally,
<code class="literal">include</code> clauses can filter using <code class="literal">partition</code> expressions.</p>
<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="_filtering_values_with_regular_expressions_2"></a>Filtering Values with regular expressions<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/terms-aggregation.asciidoc">edit</a>
</h4>
</div></div></div>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET /_search
{
    "aggs" : {
        "tags" : {
            "terms" : {
                "field" : "tags",
                "include" : ".*sport.*",
                "exclude" : "water_.*"
            }
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/534.console"></div>
<p>In the above example, buckets will be created for all the tags that has the word <code class="literal">sport</code> in them, except those starting
with <code class="literal">water_</code> (so the tag <code class="literal">water_sports</code> will not be aggregated). The <code class="literal">include</code> regular expression will determine what
values are "allowed" to be aggregated, while the <code class="literal">exclude</code> determines the values that should not be aggregated. When
both are defined, the <code class="literal">exclude</code> has precedence, meaning, the <code class="literal">include</code> is evaluated first and only then the <code class="literal">exclude</code>.</p>
<p>The syntax is the same as <a class="xref" href="regexp-syntax.html" title="Regular expression syntax">regexp queries</a>.</p>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="_filtering_values_with_exact_values_2"></a>Filtering Values with exact values<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/terms-aggregation.asciidoc">edit</a>
</h4>
</div></div></div>
<p>For matching based on exact values the <code class="literal">include</code> and <code class="literal">exclude</code> parameters can simply take an array of
strings that represent the terms as they are found in the index:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET /_search
{
    "aggs" : {
        "JapaneseCars" : {
             "terms" : {
                 "field" : "make",
                 "include" : ["mazda", "honda"]
             }
         },
        "ActiveCarManufacturers" : {
             "terms" : {
                 "field" : "make",
                 "exclude" : ["rover", "jensen"]
             }
         }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/535.console"></div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="_filtering_values_with_partitions"></a>Filtering Values with partitions<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/terms-aggregation.asciidoc">edit</a>
</h4>
</div></div></div>
<p>Sometimes there are too many unique terms to process in a single request/response pair so
it can be useful to break the analysis up into multiple requests.
This can be achieved by grouping the field’s values into a number of partitions at query-time and processing
only one partition in each request.
Consider this request which is looking for accounts that have not logged any access recently:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET /_search
{
   "size": 0,
   "aggs": {
      "expired_sessions": {
         "terms": {
            "field": "account_id",
            "include": {
               "partition": 0,
               "num_partitions": 20
            },
            "size": 10000,
            "order": {
               "last_access": "asc"
            }
         },
         "aggs": {
            "last_access": {
               "max": {
                  "field": "access_date"
               }
            }
         }
      }
   }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/536.console"></div>
<p>This request is finding the last logged access date for a subset of customer accounts because we
might want to expire some customer accounts who haven’t been seen for a long while.
The <code class="literal">num_partitions</code> setting has requested that the unique account_ids are organized evenly into twenty
partitions (0 to 19). and the <code class="literal">partition</code> setting in this request filters to only consider account_ids falling
into partition 0. Subsequent requests should ask for partitions 1 then 2 etc to complete the expired-account analysis.</p>
<p>Note that the <code class="literal">size</code> setting for the number of results returned needs to be tuned with the <code class="literal">num_partitions</code>.
For this particular account-expiration example the process for balancing values for <code class="literal">size</code> and <code class="literal">num_partitions</code> would be as follows:</p>
<div class="olist orderedlist">
<ol class="orderedlist">
<li class="listitem">
Use the <code class="literal">cardinality</code> aggregation to estimate the total number of unique account_id values
</li>
<li class="listitem">
Pick a value for <code class="literal">num_partitions</code> to break the number from 1) up into more manageable chunks
</li>
<li class="listitem">
Pick a <code class="literal">size</code> value for the number of responses we want from each partition
</li>
<li class="listitem">
Run a test request
</li>
</ol>
</div>
<p>If we have a circuit-breaker error we are trying to do too much in one request and must increase <code class="literal">num_partitions</code>.
If the request was successful but the last account ID in the date-sorted test response was still an account we might want to
expire then we may be missing accounts of interest and have set our numbers too low. We must either</p>
<div class="ulist itemizedlist">
<ul class="itemizedlist">
<li class="listitem">
increase the <code class="literal">size</code> parameter to return more results per partition (could be heavy on memory) or
</li>
<li class="listitem">
increase the <code class="literal">num_partitions</code> to consider less accounts per request (could increase overall processing time as we need to make more requests)
</li>
</ul>
</div>
<p>Ultimately this is a balancing act between managing the Elasticsearch resources required to process a single request and the volume
of requests that the client application must issue to complete a task.</p>
</div>

</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="_multi_field_terms_aggregation"></a>Multi-field terms aggregation<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/terms-aggregation.asciidoc">edit</a>
</h3>
</div></div></div>
<p>The <code class="literal">terms</code> aggregation does not support collecting terms from multiple fields
in the same document.  The reason is that the <code class="literal">terms</code> agg doesn’t collect the
string term values themselves, but rather uses
<a class="xref" href="search-aggregations-bucket-terms-aggregation.html#search-aggregations-bucket-terms-aggregation-execution-hint" title="Execution hint">global ordinals</a>
to produce a list of all of the unique values in the field.  Global ordinals
results in an important performance boost which would not be possible across
multiple fields.</p>
<p>There are two approaches that you can use to perform a <code class="literal">terms</code> agg across
multiple fields:</p>
<div class="variablelist">
<dl class="variablelist">
<dt>
<span class="term">
<a class="xref" href="search-aggregations-bucket-terms-aggregation.html#search-aggregations-bucket-terms-aggregation-script" title="Script">Script</a>
</span>
</dt>
<dd>
Use a script to retrieve terms from multiple fields.  This disables the global
ordinals optimization and will be slower than collecting terms from a single
field, but it gives you the flexibility to implement this option at search
time.
</dd>
<dt>
<span class="term">
<a class="xref" href="copy-to.html" title="copy_to"><code class="literal">copy_to</code> field</a>
</span>
</dt>
<dd>
If you know ahead of time that you want to collect the terms from two or more
fields, then use <code class="literal">copy_to</code> in your mapping to create a new dedicated field at
index time which contains the values from both fields.  You can aggregate on
this single field, which will benefit from the global ordinals optimization.
</dd>
</dl>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="search-aggregations-bucket-terms-aggregation-collect"></a>Collect mode<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/terms-aggregation.asciidoc">edit</a>
</h3>
</div></div></div>
<p>Deferring calculation of child aggregations</p>
<p>For fields with many unique terms and a small number of required results it can be more efficient to delay the calculation
of child aggregations until the top parent-level aggs have been pruned. Ordinarily, all branches of the aggregation tree
are expanded in one depth-first pass and only then any pruning occurs.
In some scenarios this can be very wasteful and can hit memory constraints.
An example problem scenario is querying a movie database for the 10 most popular actors and their 5 most common co-stars:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET /_search
{
    "aggs" : {
        "actors" : {
             "terms" : {
                 "field" : "actors",
                 "size" : 10
             },
            "aggs" : {
                "costars" : {
                     "terms" : {
                         "field" : "actors",
                         "size" : 5
                     }
                 }
            }
         }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/537.console"></div>
<p>Even though the number of actors may be comparatively small and we want only 50 result buckets there is a combinatorial explosion of buckets
during calculation - a single actor can produce n² buckets where n is the number of actors. The sane option would be to first determine
the 10 most popular actors and only then examine the top co-stars for these 10 actors. This alternative strategy is what we call the <code class="literal">breadth_first</code> collection
mode as opposed to the <code class="literal">depth_first</code> mode.</p>
<div class="note admon">
<div class="icon"></div>
<div class="admon_content">
<p>The <code class="literal">breadth_first</code> is the default mode for fields with a cardinality bigger than the requested size or when the cardinality is unknown (numeric fields or scripts for instance).
It is possible to override the default heuristic and to provide a collect mode directly in the request:</p>
</div>
</div>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET /_search
{
    "aggs" : {
        "actors" : {
             "terms" : {
                 "field" : "actors",
                 "size" : 10,
                 "collect_mode" : "breadth_first" <a id="CO244-1"></a><i class="conum" data-value="1"></i>
             },
            "aggs" : {
                "costars" : {
                     "terms" : {
                         "field" : "actors",
                         "size" : 5
                     }
                 }
            }
         }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/538.console"></div>
<div class="calloutlist">
<table border="0" summary="Callout list">
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO244-1"><i class="conum" data-value="1"></i></a></p>
</td>
<td align="left" valign="top">
<p>the possible values are <code class="literal">breadth_first</code> and <code class="literal">depth_first</code></p>
</td>
</tr>
</table>
</div>
<p>When using <code class="literal">breadth_first</code> mode the set of documents that fall into the uppermost buckets are
cached for subsequent replay so there is a memory overhead in doing this which is linear with the number of matching documents.
Note that the <code class="literal">order</code> parameter can still be used to refer to data from a child aggregation when using the <code class="literal">breadth_first</code> setting - the parent
aggregation understands that this child aggregation will need to be called first before any of the other child aggregations.</p>
<div class="warning admon">
<div class="icon"></div>
<div class="admon_content">
<p>Nested aggregations such as <code class="literal">top_hits</code> which require access to score information under an aggregation that uses the <code class="literal">breadth_first</code>
collection mode need to replay the query on the second pass but only for the documents belonging to the top buckets.</p>
</div>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="search-aggregations-bucket-terms-aggregation-execution-hint"></a>Execution hint<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/terms-aggregation.asciidoc">edit</a>
</h3>
</div></div></div>
<p>There are different mechanisms by which terms aggregations can be executed:</p>
<div class="ulist itemizedlist">
<ul class="itemizedlist">
<li class="listitem">
by using field values directly in order to aggregate data per-bucket (<code class="literal">map</code>)
</li>
<li class="listitem">
by using global ordinals of the field and allocating one bucket per global ordinal (<code class="literal">global_ordinals</code>)
</li>
</ul>
</div>
<p>Elasticsearch tries to have sensible defaults so this is something that generally doesn’t need to be configured.</p>
<p><code class="literal">global_ordinals</code> is the default option for <code class="literal">keyword</code> field, it uses global ordinals to allocates buckets dynamically
so memory usage is linear to the number of values of the documents that are part of the aggregation scope.</p>
<p><code class="literal">map</code> should only be considered when very few documents match a query. Otherwise the ordinals-based execution mode
is significantly faster. By default, <code class="literal">map</code> is only used when running an aggregation on scripts, since they don’t have
ordinals.</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET /_search
{
    "aggs" : {
        "tags" : {
             "terms" : {
                 "field" : "tags",
                 "execution_hint": "map" <a id="CO245-1"></a><i class="conum" data-value="1"></i>
             }
         }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/539.console"></div>
<div class="calloutlist">
<table border="0" summary="Callout list">
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO245-1"><i class="conum" data-value="1"></i></a></p>
</td>
<td align="left" valign="top">
<p>The possible values are <code class="literal">map</code>, <code class="literal">global_ordinals</code></p>
</td>
</tr>
</table>
</div>
<p>Please note that Elasticsearch will ignore this execution hint if it is not applicable and that there is no backward compatibility guarantee on these hints.</p>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="_missing_value_17"></a>Missing value<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/terms-aggregation.asciidoc">edit</a>
</h3>
</div></div></div>
<p>The <code class="literal">missing</code> parameter defines how documents that are missing a value should be treated.
By default they will be ignored but it is also possible to treat them as if they
had a value.</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET /_search
{
    "aggs" : {
        "tags" : {
             "terms" : {
                 "field" : "tags",
                 "missing": "N/A" <a id="CO246-1"></a><i class="conum" data-value="1"></i>
             }
         }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/540.console"></div>
<div class="calloutlist">
<table border="0" summary="Callout list">
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO246-1"><i class="conum" data-value="1"></i></a></p>
</td>
<td align="left" valign="top">
<p>Documents without a value in the <code class="literal">tags</code> field will fall into the same bucket as documents that have the value <code class="literal">N/A</code>.</p>
</td>
</tr>
</table>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="_mixing_field_types"></a>Mixing field types<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/terms-aggregation.asciidoc">edit</a>
</h3>
</div></div></div>
<div class="warning admon">
<div class="icon"></div>
<div class="admon_content">
<p>When aggregating on multiple indices the type of the aggregated field may not be the same in all indices.
Some types are compatible with each other (<code class="literal">integer</code> and <code class="literal">long</code> or <code class="literal">float</code> and <code class="literal">double</code>) but when the types are a mix
of decimal and non-decimal number the terms aggregation will promote the non-decimal numbers to decimal numbers.
This can result in a loss of precision in the bucket values.</p>
</div>
</div>
</div>

</div>
<div class="navfooter">
<span class="prev">
<a href="search-aggregations-bucket-significanttext-aggregation.html">« Significant Text Aggregation</a>
</span>
<span class="next">
<a href="search-aggregations-bucket-range-field-note.html">Subtleties of bucketing range fields »</a>
</span>
</div>
</div>

                  <!-- end body -->
                </div>
                <div class="col-xs-12 col-sm-4 col-md-4" id="right_col">
                  <div id="rtpcontainer" style="display: block;">
                    <div class="mktg-promo">
                      <h3>Most Popular</h3>
                      <ul class="icons">
                        <li class="icon-elasticsearch-white"><a href="https://www.elastic.co/webinars/getting-started-elasticsearch?baymax=default&amp;elektra=docs&amp;storm=top-video">Get Started with Elasticsearch: Video</a></li>
                        <li class="icon-kibana-white"><a href="https://www.elastic.co/webinars/getting-started-kibana?baymax=default&amp;elektra=docs&amp;storm=top-video">Intro to Kibana: Video</a></li>
                        <li class="icon-logstash-white"><a href="https://www.elastic.co/webinars/introduction-elk-stack?baymax=default&amp;elektra=docs&amp;storm=top-video">ELK for Logs &amp; Metrics: Video</a></li>
                      </ul>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </section>

        </div>


<div id="elastic-footer"></div>
<script src="https://www.elastic.co/elastic-footer.js"></script>
<!-- Footer Section end-->

      </section>
    </div>

<script src="/guide/static/jquery.js"></script>
<script type="text/javascript" src="/guide/static/docs.js"></script>
<script type="text/javascript">
  window.initial_state = {}</script>
  </body>
</html>
